import { Tool } from "@anthropic-ai/sdk/resources/messages/messages";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { FunctionCallTool, readMcpConfig } from "./mcp_bridge";

export const mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
export const transports: { [key: string]: StdioClientTransport } = {};
export const mcpTools: Tool[] = [];
export const functionCallTools: FunctionCallTool[] = [];

export async function initMcpClient() {
    const mcpConfig = readMcpConfig();
    const mcpServers = Object.entries(mcpConfig.mcpServers || {}).map(
        ([name, config]) => {
            config.name = config.name || name;
            return config;
        },
    );
    // start all mcp servers
    mcpServers.forEach((serverConfig) => {
        const serverName = serverConfig.name || "";
        if (!serverName) {
            throw new Error("MCP server name is required");
        }
        if (transports[serverName]) {
            throw new Error(`MCP server ${serverConfig.name} already exists`);
        }
        const transport = new StdioClientTransport({
            command: serverConfig.command,
            args: serverConfig.args,
        });
        transports[serverName] = transport;
        mcp.connect(transport);
    });
    const toolsResult = await mcp.listTools();
    toolsResult.tools.forEach((tool) => {
        mcpTools.push({
            name: tool.name,
            description: tool.description,
            input_schema: tool.inputSchema,
        });
        const required = (tool.inputSchema?.required as string[]) || [];
        functionCallTools.push({
            type: "function",
            function: {
                name: tool.name,
                description: tool.description || `Use the ${tool.name} tool`,
                parameters: {
                    type: "object",
                    properties: tool.inputSchema?.properties || {},
                    required,
                },
            },
        });
    });
    console.log("MCP client initialized");
}
export async function functionToMcpToolCall(callList: any) {
    const toolResults = [];
    for (const call of callList) {
        if (call.function) {
            const fn = call.function;
            const toolName = fn.name;
            const toolArgs = fn.arguments;
            const result = await mcp.callTool({
                name: toolName,
                arguments: toolArgs,
            });
            toolResults.push(result);
        }
    }
    return toolResults;
}
